package com.laotou99.bookManage.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.laotou99.bookManage.Auth.laotou99Realm;

@Controller("LoginAction")
@RequestMapping("/login")
public class LoginAction {
	private static final Log logger = 
			LogFactory.getLog(LoginAction.class);
	
	@RequestMapping("")
	public ModelAndView execute(HttpServletRequest request,
			HttpServletResponse response,
			String username,
			String password)
	{		
		logger.info("ModelAndView execute->login");
		System.out.println("ModelAndView execute->login");
		UsernamePasswordToken token = 
				new UsernamePasswordToken(username, password);
		
		token.setRememberMe(false);
		
		Subject subject = SecurityUtils.getSubject();
		
		try {
			subject.login(token);
		} catch (UnknownAccountException e) {
			e.printStackTrace();
		}catch (IncorrectCredentialsException e) {
			e.printStackTrace();
		}catch (AuthenticationException e) {
			e.printStackTrace();
		}
		
		if(subject.isAuthenticated()){			
			ModelAndView mav = new ModelAndView();
			System.out.println("username->"+username);
			//mav.addObject("message",username);
			
			mav.setViewName("redirect:/showbook");
			return mav;			
		}
		// mav.setView("redirect:/home");
		return new ModelAndView("/logoin");
	}
}
